// src/utils/dialog.js
import Vue from 'vue';
import { Dialog } from 'element-ui';

/**
 * Dialog 构造器
 * 支持字符串、组件、带 ref 的组件
 */
const DialogConstructor = Vue.extend({
  render(h) {
    let contentNode;

    // 处理 content 类型
    if (typeof this.content === 'string') {
      contentNode = h('div', {}, this.content);
    }
    else if (this.content.component) {
      // 高级对象 { component, props, on }
      contentNode = h(this.content.component, {
        props: this.content.props,
        on: this.content.on,
        ref: 'contentComponent' // ✅ 关键：加 ref
      });
    }
    else if (typeof this.content === 'object' && this.content.render) {
      // 直接传组件选项
      contentNode = h(this.content, {
        ref: 'contentComponent' // ✅ 关键
      });
    }
    else {
      contentNode = h('div', {}, '未知内容');
    }

    return h(
      Dialog,
      {
        props: {
          visible: this.visible,
          title: this.title,
          width: this.width,
          beforeClose: this.handleClose
        },
        on: {
          close: () => {
            this.visible = false;
          },
          closed: () => {
            // 安全销毁
            this.$destroy();
            if (this.$el && this.$el.parentNode) {
              this.$el.parentNode.removeChild(this.$el);
            }
          }
        }
      },
      [
        // 内容区域
        contentNode,

        // 底部按钮
        h('div', { slot: 'footer', style: 'text-align: right;' }, [
          h('el-button', {
            on: { click: this.onCancel }
          }, this.cancelButtonText || '取 消'),

          h('el-button', {
            props: { type: 'primary' },
            on: { click: this.onConfirm }
          }, this.confirmButtonText || '确 定')
        ])
      ]
    );
  },

  data() {
    return {
      visible: false,
      title: '提示',
      content: '',
      width: '30%',
      beforeClose: null,
      onConfirm: () => {}, // 避免 null handler 警告
      onCancel: () => {},
      confirmButtonText: '确 定',
      cancelButtonText: '取 消'
    };
  },

  methods: {
    handleClose(done) {
      if (typeof this.beforeClose === 'function') {
        this.beforeClose(done);
      } else {
        done();
      }
    }
  }
});

// 单例实例（避免重复）
let instance = null;

/**
 * 自定义弹窗函数
 */
function CustomDialog(options = {}) {
  // 销毁旧实例
  if (instance) {
    instance.$destroy();
    if (instance.$el && instance.$el.parentNode) {
      instance.$el.parentNode.removeChild(instance.$el);
    }
    instance = null;
  }

  // 处理参数
  if (typeof options === 'string') {
    options = { content: options };
  }

  const {
    title = '提示',
    content = '',
    width = '30%',
    beforeClose = null,
    confirmButtonText = '确 定',
    cancelButtonText = '取 消',
    onConfirm = null,
    onCancel = null
  } = options;

  // 创建新实例
  instance = new DialogConstructor({
    el: document.createElement('div'),
    data: {
      title,
      content,
      width,
      beforeClose,
      confirmButtonText,
      cancelButtonText
    }
  });

  // 插入 body
  document.body.appendChild(instance.$el);

  // === 确定按钮逻辑 ===
  instance.onConfirm = () => {
    const close = () => { instance.visible = false; };

    if (typeof onConfirm === 'function') {
      let data = null;
      /**
       * @type {Vue & { getData?: () => any }} child
       */
      const child = instance.$refs.contentComponent; // ✅ 通过 ref 获取

      if (child) {
        if (typeof child.getData === 'function') {
          data = child.getData(); // 推荐方式
          // console.log('[Dialog] getData() 返回:', data);
        } else {
          // 回退：直接读取 $data
          // data = {fallback: true };
          data = { error: '无法获取子组件getData' };
          // console.warn('[Dialog] 使用 $data 回退获取数据:', data);
        }
      } else {
        data = { error: '无法获取 content 组件实例' };
        // console.error('[Dialog] $refs.contentComponent 为 null');
      }

      // 调用用户回调
      onConfirm(close, data);
    } else {
      close();
    }
  };

  // === 取消按钮逻辑 ===
  instance.onCancel = () => {
    if (typeof onCancel === 'function') {
      onCancel();
    }
    instance.visible = false;
  };

  // 显示
  Vue.nextTick(() => {
    instance.visible = true;
  });

  return instance;
}

export default CustomDialog;
